package com.cpc.mback.controller;


import com.alibaba.fastjson.JSONObject;
import com.cpc.mback.RespEntity;
import com.cpc.mback.entity.Content;
import com.cpc.mback.entity.Record;
import com.cpc.mback.entity.User;
import com.cpc.mback.service.MainService;
import com.cpc.mback.service.RecordService;
import com.cpc.mback.service.UploadService;
import com.cpc.mback.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

@RestController
@Api(value = "主要接口",tags="主要接口",description ="没有description" )
@RequestMapping("/api/main")
public class MainController {


    @Autowired
    MainService mainService;

    @Autowired
    UploadService uploadService;
    @Autowired
    RecordService recordService;
    @Autowired
    UserService userService;


    @ApiOperation(value = "全部内容接口", notes = "该接口为备用接口")

    @GetMapping
    public Page<Content> page(@RequestParam(defaultValue = "1") Integer page,
                              @RequestParam(defaultValue = "10") Integer size) {
        return mainService.page(PageRequest.of(page - 1, size));
    }


    @ApiOperation(value = "问答首页：全部问答的问题", notes = "参数正确，可参照自动生成的格式")
    @GetMapping("/qa")
    public Page<Content> getQaContent(@RequestParam(defaultValue = "1") Integer page,
                                            @RequestParam(defaultValue = "10") Integer size) {

        Content.Type type = Content.Type.qa;
        return mainService.getMain(type,PageRequest.of(page - 1, size));
    }

    @ApiOperation(value = "笔记首页：全部笔记", notes = "参数正确，可参照自动生成的格式")
    @GetMapping("/standard")
    public ResponseEntity getStandardContent(@RequestParam(defaultValue = "1") Integer page,
                                        @RequestParam(defaultValue = "10") Integer size) {

        Content.Type type = Content.Type.standard;


        return ResponseEntity.status(200).body(RespEntity.code(200).body(mainService.getMain(type,PageRequest.of(page - 1, size))).build());

        //return mainService.getMain(type,PageRequest.of(page - 1, size));
    }

    @GetMapping("/mall")
    @ApiOperation(value = "老接口，暂时不用", notes = "")
    public Page<Content> getMallContent(@RequestParam(defaultValue = "1") Integer page,
                                        @RequestParam(defaultValue = "10") Integer size) {
        Content.Type type = Content.Type.mall;
        return mainService.getMain(type,PageRequest.of(page - 1, size));
    }

    @GetMapping("/author")
    @ApiOperation(value = "老接口，暂时不用", notes = "")
    public Page<Content> getAuthorContent(@RequestParam(defaultValue = "1") Integer page,
                                        @RequestParam(defaultValue = "10") Integer size) {
        Content.Type type = Content.Type.author;
        return mainService.getMain(type,PageRequest.of(page - 1, size));
    }

    /* @ApiOperation(value = "老接口，暂时不用", notes = "")
     @GetMapping("/get")
     public ResponseEntity getInfo(@RequestBody Payload payload) {

         if (userService.checkRegistered(payload.openId)){
             Content content = mainService.fetch(Long.valueOf(payload.id));
             recordService.createRecord(Long.valueOf(payload.openId),Long.valueOf(payload.id),"",0);
             return ResponseEntity.status(200).body(RespEntity.code(200).body(content).build());
         }else {
             userService.SignUp(payload.openId);
             Content content = mainService.fetch(Long.valueOf(payload.id));
             recordService.createRecord(Long.valueOf(payload.openId),Long.valueOf(payload.id),"",0);
             return ResponseEntity.status(200).body(RespEntity.code(200).body(content).build());
         }
        Content content = mainService.fetch(Long.valueOf(payload.id));
        recordService.createRecord(payload.openId,Long.valueOf(payload.id),"",0,false);
        return ResponseEntity.status(200).body(RespEntity.code(200).body(content).build());
        //JSONObject result = new JSONObject();

    }

    @ApiOperation(value = "问答的回答：指定问题的回答", notes = "参数正确，可参照自动生成的格式")
    @GetMapping("/get-comments")
    public ResponseEntity getComments(@RequestParam String  id,@RequestParam String openId, @RequestParam(defaultValue = "1") Integer page,
                                    @RequestParam(defaultValue = "10") Integer size) {


        //return recordService.getRecord(Long.valueOf(id), openId,PageRequest.of(page - 1, size));
        return ResponseEntity.status(200).body(RespEntity.code(200).body(recordService.getRecord(Long.valueOf(id), openId,PageRequest.of(page - 1, size))).build());

    }

    @ApiOperation(value = "通用上传记录", notes = "参数只需要payload 里边的openId,id(content.id),content,type\n  sub 字段为判断是否为record的子record,如评论的评论，含义为子‘度数’，目前只支持1，默认为0" +
            "0 代表普通记录,1为评论或者回答，2为关注，3为收藏，4为点赞 ")
    @PostMapping("/post-record")
    public ResponseEntity postRecord(@RequestBody Payload payload) {
        if (payload.sub.equals(1)){
            Record record=recordService.createRecord(payload.openId,Long.valueOf(payload.id),payload.content,Integer.parseInt(payload.type),true);

        }
        Record record=recordService.createRecord(payload.openId,Long.valueOf(payload.id),payload.content,Integer.parseInt(payload.type),false);


        return ResponseEntity.status(200).body(RespEntity.code(200).body(record).build());

    }*/
/*
    @ApiOperation(value = "通用上传内容/咨询内容也放入其中", notes = "参数只需要payload 里边的title,id(id应为用户的openId),content,type\n 其中咨询内容多了time 和 amount两项" +
            "0 代表普通记录,1问答 " +
            "\n{\n" +
            "  \"amount\": \"\",\n" +
            "  \"content\": \"string\",\n" +
            "  \"type\": \"0\",\n" +
            "  \"id\": \"123\",\n" +
            "  \"time\": \"\",\n" +
            "  \"title\": \"string\"\n" +
            "}解释，Amount和time是咨询时候写的，平时空的字符串就可以，content放主要内容" +
            "\n,type为0是笔记，为1是问答，id是用户的openId,title是标题，然后笔记还有一个参数是sort，" +
            "\n详情如下\n  if(sort.equals(\"0\")){\n" +
            "            content1.setSort(Content.Sort.inSchool);\n" +
            "        }\n" +
            "        if(sort.equals(\"1\")){\n" +
            "            content1.setSort(Content.Sort.up);        }\n" +
            "        if(sort.equals(\"2\")){\n" +
            "            content1.setSort(Content.Sort.hotIndustry);        }\n" +
            "        if(sort.equals(\"3\")){\n" +
            "            content1.setSort(Content.Sort.internship);        }\n" +
            "        if(sort.equals(\"4\")){\n" +
            "            content1.setSort(Content.Sort.findJob);        }\n" +
            "        if(sort.equals(\"5\")){\n" +
            "            content1.setSort(Content.Sort.resource);        }\n" +
            "        if(sort.equals(\"6\")){\n" +
            "            content1.setSort(Content.Sort.fun);        }\n" +
            "        if(sort.equals(\"7\")){\n" +
            "            content1.setSort(Content.Sort.sci); ")
    @PostMapping("/post-content")
    public ResponseEntity postContent(@RequestBody Payload payload) {

//        if(payload.type.equals("8")){
//            Content content = mainService.createContent(payload.title,Long.valueOf(payload.id),payload.content,Integer.parseInt(payload.type));
//
//        }

        Content content = mainService.createContent(payload.title,payload.openId,
                payload.content,Integer.parseInt(payload.type),
                payload.time,payload.amount,payload.sort,payload.sort2,payload.sort3
                ,payload.img1,payload.img2,payload.img3
                ,payload.img4,payload.img5,payload.img6
                ,payload.img7,payload.img8,payload.img9
                ,payload.vid);
        return ResponseEntity.status(201).body(RespEntity.code(200).body(content).build());

    }*/

    @ApiOperation(value = "上传用户信息", notes = "参数\n" +
            " ")
    @PostMapping("/sign-up")
    public ResponseEntity postUser(@RequestBody UserPayload payload) {

        User user = userService.SignUp(payload.openId,payload.name,payload.gender,payload.inviteCode,payload.styleSign,payload.intro,payload.avatar);
        return ResponseEntity.status(200).body(RespEntity.code(200).body(user).build());

    }

    @ApiOperation(value = "修改用户信息", notes = "参数\n" +
            " ")
    @PostMapping("/modify-user")
    public ResponseEntity modifyUser(@RequestBody UserPayload payload) {

        User user = userService.ModifyUser(payload.openId,payload.name,payload.gender,payload.inviteCode,payload.styleSign,payload.intro,payload.avatar);
        return ResponseEntity.status(200).body(RespEntity.code(200).body(user).build());

    }
    @ApiOperation(value = "验证是否注册", notes = "参数\n" +
            " ")
    @GetMapping("/verify")
    public boolean verify(@RequestParam String openId) {

        return userService.checkRegistered(openId);

    }

    @ApiOperation(value = "fetch用户信息", notes = "参数 openId\n" +
            " ")
    @GetMapping("/fetch")
    public User fetchUser(@RequestParam String openId) {

        return userService.fetchUser(openId);

    }

    @ApiOperation(value = "受询者认证", notes = "参数 完整的payload\n" +
            " ")
    @PostMapping("/verti")
    public User certificateUser(@RequestBody VipUserPayload payload ) {

        return userService.Certificate( payload.openId,payload.name,payload.weChatNumber,
                payload.phone, payload.email,
                payload.fee,payload.spareTime, payload.description,payload.mt1,
                payload.mt2,payload.mt3,payload.ad1,payload.ad3,payload.ad2,payload.profession,payload.school);

    }

    public static File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @ApiOperation(value = "上传", notes = "上传文件获取 url \n" +
            " ")
    @PostMapping("/upload")
    public ResponseEntity upload(@RequestParam(value = "file") MultipartFile file ) throws Exception {

        String fileName = file.getOriginalFilename();
        File file2 = multipartFileToFile(file);
        String resultUrl = uploadService.uploadOSS(file2);

        return ResponseEntity.status(200).body(RespEntity.code(200).message("更换成功:"+resultUrl).body(resultUrl).build());


    }
        @Data
        private static class Payload {
            private String title;
            private String type;
            private String id;
            private String openId;
            private String content;
            private int intType;
            String sub;
            private String time;
            private String amount;
            private String sort;
            private String sort2;
            private String sort3;
            private String img1;
            private String img2;
            private String img3;
            private String img4;
            private String img5;
            private String img6;
            private String img7;
            private String img8;
            private String img9;
            private String vid;
        }
    @Data
    private static class UserPayload {
        private String name;
        private String gender;
        private String inviteCode;
        private String openId;
        private String styleSign;
        private String intro;
        private String avatar;
    }
    @Data
    private static class VipUserPayload {
        String openId;
        String name;
        String weChatNumber;
        String phone;
        String email;
        String fee;
        String spareTime;
        String description;
        String mt1;
        String mt2;
        String mt3;
        String ad1;
        String ad3;
        String ad2;
        String profession;
        String school;
    }
}
